package com.ft.oa.service.project.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ft.oa.domain.Attachment;
import com.ft.oa.domain.dto.ApiResult;
import com.ft.oa.domain.dto.knowledgeBase.AttachmentDto;
import com.ft.oa.domain.project.CompanyQualification;
import com.ft.oa.domain.project.CompanyQualificationPage;
import com.ft.oa.enums.DirectoryTypeEnum;
import com.ft.oa.enums.ManagerEnum;
import com.ft.oa.mapper.attachment.AttachmentMapper;
import com.ft.oa.mapper.bidProjectMapper.CompanyQualificationMapper;
import com.ft.oa.service.knowledgeBase.DirectoryService;
import com.ft.oa.service.project.CompanyQualificationService;
import com.ft.oa.utils.FileUtil;
import com.ft.oa.utils.SecurityUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公司资质维护
 * @author liyansheng
 * @ClassName CompanyQualificationServiceImpl
 * @date 2022-1-5 16:09:29
 */
@Service
public class CompanyQualificationServiceImpl implements CompanyQualificationService {
    //附件上传位置
    @Value("${file.upload.url}")
    private String uploadFilePath;

    @Resource
    private CompanyQualificationMapper companyQualificationMapper;

    @Resource
    private AttachmentMapper attachmentMapper;

    @Resource
    private DirectoryService directoryService;

    /**
     * 新增招投标项目
     * @param qualification
     * @return
     */
    @Override
    @Transactional
    public ApiResult add(CompanyQualification qualification) {
        List<AttachmentDto> attachments = qualification.getAttachments();
        if(attachments != null && attachments.size() > 0){
            String json = JSONArray.toJSONString(attachments);
            qualification.setAchment(json);
        }else{
            qualification.setAchment(null);
        }
        companyQualificationMapper.insert(qualification);
        /**
         *
         *             FILING_BID_QUALIFICATIONS("filing_bid_qualifications","归档文件-招投标-公司资质"),
         *                     FILING_BID_EXPERIENCE("filing_bid_experience","归档文件-招投标-招投标经验"),
         *                     FILING_BID_MATERIAL("filing_bid_material","归档文件-招投标-经典素材"),
         * 保存附件项目相关的公共方法
         *
         * @param attachments 附件集合
         * @param source      来源  根据 DirectoryTypeEnum
         * @param relationId  业务id
         * @param sourceId    如果一个表单有多个附件，用于标识附件属于表单的哪个附件
         * @param  projectNumber 项目编号 全局唯一
         */
        if(attachments != null && attachments.size() > 0) {
                //公司资质
               if(qualification.getTabType().equals("qualifications")){
                   directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_QUALIFICATIONS.getCode(), String.valueOf(qualification.getId()), null, "");
               }else if(qualification.getTabType().equals("experience") ){
                    //经验
                   directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_EXPERIENCE.getCode(), String.valueOf(qualification.getId()), null, "");
               }else if(qualification.getTabType().equals("partnerinformation")){
                    //合作伙伴
                   directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_PARTNER.getCode(), String.valueOf(qualification.getId()), null, "");
               }else{
                    //今典素材
                   directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_MATERIAL.getCode(), String.valueOf(qualification.getId()), null, "");
               }

        }
        return ApiResult.simpleSuccess();
    }

    /**
     * 修改招投标项目
     * @param qualification
     * @return
     */
    @Override
    @Transactional
    public ApiResult edit(CompanyQualification qualification) {
        List<AttachmentDto> attachments = qualification.getAttachments();
        if(attachments != null && attachments.size() > 0){
            String json = JSONArray.toJSONString(attachments);
            qualification.setAchment(json);
        }else{
            qualification.setAchment(null);
        }
        qualification.setId(qualification.getId());
        qualification.setUpdateTime(LocalDateTime.now());
        companyQualificationMapper.updateById(qualification);

        if(attachments != null && attachments.size() > 0) {
            //公司资质
            if(qualification.getTabType().equals("qualifications")){
                directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_QUALIFICATIONS.getCode(), String.valueOf(qualification.getId()), null, "");
            }else if(qualification.getTabType().equals("experience") ){
                //经验
                directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_EXPERIENCE.getCode(), String.valueOf(qualification.getId()), null, "");
            }else if(qualification.getTabType().equals("partnerinformation")){
                //合作伙伴
                directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_PARTNER.getCode(), String.valueOf(qualification.getId()), null, "");
            }else{
                //今典素材
                directoryService.saveProAttachment(attachments, DirectoryTypeEnum.FILING_BID_MATERIAL.getCode(), String.valueOf(qualification.getId()), null, "");
            }

        }
        return ApiResult.simpleSuccess();
    }

    /**
     * 删除招投标项目
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ApiResult del(Long id) {
        LambdaUpdateChainWrapper<CompanyQualification> wrapper = new LambdaUpdateChainWrapper<>(companyQualificationMapper);
        wrapper.eq(CompanyQualification::getId,id)
                .set(CompanyQualification::getDellcompany,"1")
                .update();
        return ApiResult.simpleSuccess();
    }

    /**
     * 根究主键查询招投标项目
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ApiResult selectById(Long id,String tabType) {
        QueryWrapper<CompanyQualification> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CompanyQualification::getId,id)
                .eq(CompanyQualification::getTabType,tabType);
        CompanyQualification qualification = companyQualificationMapper.selectOne(queryWrapper);
            String achment = qualification.getAchment();
        if(StringUtils.hasText(achment)){
            qualification.setAchment("");
            qualification.setAttachments(JSONArray.parseArray(achment, AttachmentDto.class));
        }

        return ApiResult.successWithData(qualification);
    }

    /**
     * 分页查询公司资质
     * @param qualificationPage
     * @return
     */
    @Override
    public ApiResult page(CompanyQualificationPage qualificationPage) {
        QueryWrapper<CompanyQualification> queryWrapper = new QueryWrapper<>();
        Page<CompanyQualification> page = new Page<>(qualificationPage.getPage(),qualificationPage.getSize());
        queryWrapper.lambda()
                .eq(CompanyQualification::getTabType,qualificationPage.getTabType())
                .eq(ManagerEnum.GENERAL.toString().equals(SecurityUtils.getCurrentUser().getManager()), CompanyQualification::getCreator,SecurityUtils.getCurrentUser().getId())
                .eq(CompanyQualification::getDellcompany,"0")
                .like(StringUtils.hasText(qualificationPage.getName()),CompanyQualification::getName,qualificationPage.getName())
                .like(StringUtils.hasText(qualificationPage.getBelongsTo()),CompanyQualification::getBelongsTo,qualificationPage.getBelongsTo())
                .eq(qualificationPage.getType()!=null&&qualificationPage.getType()>=0,CompanyQualification::getType,qualificationPage.getType());
        IPage<CompanyQualification> pages = companyQualificationMapper.selectPage(page,queryWrapper);
        List<CompanyQualification> records = pages.getRecords();
        records.forEach(e->{
            String achment = e.getAchment();
            e.setAchment("");
            e.setAttachments(JSONObject.parseArray(achment, AttachmentDto.class));
        });
        return ApiResult.successWithData(pages);
    }


    /**
     * 附件上传记录
     * @param files
     * @return
     */
    @Override
    @Transactional
    public ApiResult upload(MultipartFile files[], String source) {
        //记录文件上传信息
        ArrayList<Attachment> fileList = new ArrayList<Attachment>();
        for (MultipartFile myFile:files) {
            Attachment attachment = new Attachment();
            // 获取文件名称
            String filename = FilenameUtils.getBaseName(myFile.getOriginalFilename());
            //获取后缀名称
            String ext = FilenameUtils.getExtension(myFile.getOriginalFilename());
            String rebuildFileName = filename+System.currentTimeMillis();
            attachment.setName(filename);
            attachment.setFileName(rebuildFileName);
            attachment.setType(ext);
            attachment.setSource(source);
            attachment.setPath(uploadFilePath);
            attachmentMapper.insert(attachment);
            fileList.add(attachment);
        }
        //调用公共方法上传附件
        HashMap<String, List<String>> hashMap = FileUtil.getFileUpload(files, uploadFilePath);
        if(hashMap.isEmpty()){
            return ApiResult.builder().msg("文件上传失败").build();
        }else{
            //上传成功后把附件表主键信息传给前端
            List<Long> resultList = fileList.stream().map(Attachment::getId).collect(Collectors.toList());
            String uploadIds = org.apache.commons.lang3.StringUtils.join(resultList.toArray(),",");
            return ApiResult.successWithData(uploadIds);
        }
    }
}
